/**
 * date:2020/02/27
 * author:Mr.Chung
 * version:2.0
 * description:layuimini tab框架扩展
 */
layui.define(["layer", "jquery"], function (exports) {
    var layer = layui.layer,
        $ = layui.$,
        tabs = layui.tabs,
        dropdown = layui.dropdown;


    var miniTab = {
        /**
         * 初始化tab
         * @param options
         */
        options: {},
        render: function (options) {
            miniTab.options = options
            options.id = options.id || null;
            options.menuList = options.menuList || [];  // todo 后期菜单想改为不操作dom, 而是直接操作初始化传过来的数据
            options.homeInfo = options.homeInfo || {};
            options.dropdown_instance = miniTab.add_dropdown(options);
            miniTab.listen(options);
            miniTab.init_tabs(options);
            miniTab.listenHash(options);
        },

        /**
         * 初始化tabs,主要是欢迎页
         * @param options.id
         */
        init_tabs: function (options) {
            tabs.render({
                elem: '#' + options.id,
                header: [
                    {title: options.homeInfo.title, closable: false, id: options.homeInfo.href},
                ],
                body: [
                    {content: '<iframe width="100%" height="100%" frameborder="no" border="0" marginwidth="0" marginheight="0"   src="' + options.homeInfo.href + '"></iframe>'},
                ],
                index: 0, // 初始选中标签索引
            })
        },

        /**
         * 监听hash变化
         * @param options
         * @returns {boolean}
         */
        listenHash: function (options) {
            options.homeInfo = options.homeInfo || {};
            options.menuList = options.menuList || [];
            if (!options.urlHashLocation) return false;
            var tabId = location.hash.replace(/^#\//, '');
            if (tabId === null || tabId === undefined || tabId === '') return false;
            // 判断是否为首页
            if (tabId === options.homeInfo.href) return false;
            // 判断是否为右侧菜单
            var menu = miniTab.searchMenu(tabId, options.menuList);
            if (menu !== undefined) {
                miniTab.create({
                    id: options.id,
                    dropdown_instance: options.dropdown_instance,
                    tabId: tabId,
                    href: tabId,
                    title: menu.title,
                    urlHashLocation: options.urlHashLocation
                });
                return false;
            }
        },

        /**
         * 增加右弹框
         * @param options.id
         */
        add_dropdown: function (options) {
            // 为标签头添加上下文菜单
            let dropdown_instance = dropdown.render({
                elem: '#' + options.id + ' .layui-tabs-header>li',
                trigger: 'contextmenu',
                data: [
                    {
                        title: '刷新当前页',
                        action: 'refresh',
                    }, {
                        title: '刷新鼠标指定页',
                        action: 'mounse_refresh',
                    }, {
                        title: '关闭当前页',
                        action: 'close',
                        mode: 'this',
                    }, {
                        title: '关闭其它页',
                        action: 'close',
                        mode: 'other'
                    }, {
                        title: '关闭右侧标签页',
                        action: 'close',
                        mode: 'right'
                    }, {
                        title: '关闭所有页',
                        action: 'close',
                        mode: 'all'
                    }
                ],
                click: function (data, othis, event) {
                    var index = this.elem.index(); // 获取活动标签索引
                    if (data.action === 'close') { // 关闭标签操作
                        if (data.mode === 'this') {
                            tabs.close(options.id, index); // 关闭当前标签
                        } else {
                            tabs.closeMult(options.id, data.mode, index); // 批量关闭标签
                        }
                    } else if (data.action === 'mounse_refresh') {
                        let mini_tab = $('#layuiminiTab');
                        let src = mini_tab.find('.layui-tabs-header').find('li').eq(index).attr('lay-id');
                        mini_tab.find('.layui-tabs-body').find('.layui-tabs-item').eq(index).find('iframe')[0].src = src;
                    } else if (data.action === 'refresh') {
                        miniTab.reloadCurrentByIframe();
                    }
                }
            });
            return dropdown_instance;
        },

        /**
         * 刷新当前tab方法
         */
        reloadCurrentByIframe: function () {
            let mini_tab = $('#layuiminiTab');
            let iframe = mini_tab.find('.layui-tabs-body').find('.layui-show').find('iframe');
            if (iframe.length !== 0) {
                iframe[0].src = iframe[0].src;
            } else {
                console.log('当前iframe刷新失败');
            }
        },

        /**
         * 新建tab窗口
         */
        create: function (options) {
            options.tabId = options.tabId || null;
            options.href = options.href || null;
            options.title = options.title || null;
            // 添加标签到最后
            tabs.add(options.id, {
                title: options.title,
                content: '<iframe width="100%" height="100%" frameborder="no" border="0" marginwidth="0" marginheight="0"   src="' + options.href + '"></iframe>',
                // mode: 'after',
                id: options.tabId,
                done: function (params) {
                    if (options.urlHashLocation) {
                        location.hash = '/' + options.tabId;
                    }
                    dropdown.render($.extend({}, options.dropdown_instance.config, {
                        elem: params.headerItem  // 2025年6月25日：修复最后一个tab右键无效的问题
                    }));
                    //创建并且打开左侧菜单
                    miniTab.open_left_menu(options.tabId);
                }
            });
            tabs.change(options.id, options.tabId, true);
        },
        /**
         * 判断tab窗口
         */
        check: function (tabId) {
            let select_obj = parent.layui.$('#layuiminiTab').find('.layui-tabs-header').find('li[lay-id="' + tabId + '"]');
            if (select_obj.length === 0) {
                return true
            }
            return false;
        },

        /**
         * 查询菜单信息
         * @param href
         * @param menuList
         */
        searchMenu: function (href, menuList) {
            var menu;
            for (key in menuList) {
                var item = menuList[key];
                if (item.href === href) {
                    menu = item;
                    break;
                }
                if (item.child) {
                    newMenu = miniTab.searchMenu(href, item.child);
                    if (newMenu) {
                        menu = newMenu;
                        break;
                    }
                }
            }
            return menu;
        },
        /**
         * 创建好tab，将左侧设置打开状态
         * @param tabId
         */
        open_left_menu: function (tabId) {
            let a_obj = $('.layuimini-menu-left a[layuimini-href="' + tabId + '"]');
            a_obj.click();
            for (let i = 0; i <= 10; i++) { //最多检索十级菜单
                a_obj = a_obj.parent();
                if (a_obj.hasClass('layuimini-menu-left')) { //表示到顶了
                    break;
                }
                if (a_obj.is('ul')) { //取模块id值,并且打开组件
                    $('li[data-menu="' + a_obj.attr('id') + '"]').click()
                }
                if (a_obj.is('li') || a_obj.hasClass('menu-dd')) { //打开标签
                    a_obj.addClass('layui-nav-itemed')
                }
            }
        },

        /**
         * 监听
         * @param options
         */
        listen: function (options) {
            options = options || {};
            if (options.urlHashLocation) {
                tabs.on('beforeChange(' + options.id + ')', function (data) {
                    location.hash = '/' + $(this).attr('lay-id');
                });
                tabs.on('afterClose(' + options.id + ')', function (data) {
                    location.hash = '/' + $(this).attr('lay-id');
                });
            }
            //打开新窗口
            $('body').on('click', '[layuimini-href]', function () {
                var loading = layer.load(0, {shade: false, time: 2 * 1000});
                var tabId = $(this).attr('layuimini-href'),
                    href = $(this).attr('layuimini-href'),
                    title = $(this).text(),
                    target = $(this).attr('target');

                var el = $("[layuimini-href='" + href + "']", ".layuimini-menu-left");
                layer.close(window.openTips);
                if (el.length) {
                    $(el).closest(".layui-nav-tree").find(".layui-this").removeClass("layui-this");
                    $(el).parent().addClass("layui-this");
                }

                if (target === '_blank') {
                    layer.close(loading);
                    window.open(href, "_blank");
                    return false;
                }

                if (tabId === null || tabId === undefined) tabId = new Date().getTime();
                var checkTab = miniTab.check(tabId);
                if (checkTab) {
                    miniTab.create({
                        id: options.id,
                        dropdown_instance: options.dropdown_instance,
                        tabId: tabId,
                        href: href,
                        title: title,
                        urlHashLocation: options.urlHashLocation
                    });
                } else {
                    tabs.change(options.id, tabId, true);
                    if (options.urlHashLocation) {
                        location.hash = '/' + tabId;
                    }
                }
                layer.close(loading);
            });

            // tabs 切换前的事件
            tabs.on('beforeChange(' + options.id + ')', function (data) {
                let tabId = $(data.to.headerItem).attr('lay-id');
                miniTab.open_left_menu(tabId)
            });

            /**
             * 快捷打开tab窗口
             */
            window.addEventListener('message', function (event) {
                //console.log('Received message:', event.data); // 处理接收到子页面的的消息
                var loading = layer.load(0, {shade: false, time: 2 * 1000});
                var tabId = event.data.tabId,
                    href = event.data.href,
                    title = event.data.title,
                    target = event.data.target
                var el = $("[layuimini-href='" + href + "']", ".layuimini-menu-left");
                layer.close(window.openTips);
                if (el.length) {
                    $(el).closest(".layui-nav-tree").find(".layui-this").removeClass("layui-this");
                    $(el).parent().addClass("layui-this");
                }

                if (target === '_blank') {
                    layer.close(loading);
                    window.open(href, "_blank");
                    return false;
                }

                if (tabId === null || tabId === undefined) tabId = new Date().getTime();
                var checkTab = miniTab.check(tabId);
                if (checkTab) {
                    miniTab.create({
                        id: miniTab.options.id,
                        dropdown_instance: miniTab.options.dropdown_instance,
                        tabId: tabId,
                        href: href,
                        title: title,
                        urlHashLocation: miniTab.options.urlHashLocation
                    });
                } else {
                    tabs.change(miniTab.options.id, tabId, true);
                    if (miniTab.options.urlHashLocation) {
                        location.hash = '/' + tabId;
                    }
                }
                miniTab.open_left_menu(tabId)
                layer.close(loading);
            }, false);
        },
    };
    exports("miniTab", miniTab);
});